package com.ruoyi.web.controller.api.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.egdk.api.entity.MedicalCapture;
import com.egdk.api.entity.TabImagesNEntity;
import com.egdk.api.entity.TabImagesNEntityExample;
import com.egdk.api.mapp.TabImagesNEntityMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.TabPtdetail;
import com.ruoyi.system.domain.report.Patient;
import com.ruoyi.system.domain.report.vo.DICOMSeriesImgVo;
import com.ruoyi.system.domain.report.vo.SeriesVo;
import com.ruoyi.system.mapper.TabPtdetailMapper;
import com.ruoyi.system.mapper.report.PatientMapper;
import com.ruoyi.system.service.report.ITeacherService;
import com.ruoyi.web.controller.api.dto.*;
import com.ruoyi.web.controller.api.service.ApiServiceImpl;
import com.ruoyi.web.controller.tool.HttpUtils;
import com.sun.jna.platform.win32.Guid;
//import javafx.scene.control.Tab;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/tspet/")
public class ApiController {

    @Autowired
    private ITeacherService iTeacherService;

    @Autowired
    private TabImagesNEntityMapper tabImagesNEntityMapper;

    /**
     * 前端查询序列
     *
     * @param studyInsta
     * @return
     */
    @GetMapping("/getStudyInsta/{studyInsta}")
    public AjaxResult getStudyInsta(@PathVariable String studyInsta) {
        List<DICOMSeriesImgVo> seriesVos = iTeacherService.getStudyInsta(studyInsta);
        return AjaxResult.success(seriesVos);
    }

    /**
     * 将用户选择的序列传给后端,后端进行数据逻辑处理
     *
     * @param seriesVo
     * @return
     */
    @PostMapping("/openseries")
    public AjaxResult series(@RequestBody SeriesVo seriesVo) {
        apiService.series(seriesVo);
        return AjaxResult.success();
    }

    @Autowired
    private ApiServiceImpl apiService;

    /**
     * 融合软件发送请求，根据accessToken，查询上面处理好的数据
     *
     * @param accessToken
     * @return
     */
    @GetMapping("/open/{accessToken}")
    public AjaxResult getInfo(@PathVariable String accessToken) {
        JSONObject object = apiService.getInfo(accessToken);
        return AjaxResult.success(object);
    }

    /**
     * 融合软件发送请求，根据accessToken，查询ini文件数据
     *
     * @param accessToken
     * @return
     */
    @GetMapping("/getIni/{accessToken}")
    public AjaxResult getIni(@PathVariable String accessToken) {
        String content = apiService.getIni(accessToken);
        return AjaxResult.success(content);
    }


    /**
     * 根据uuid下载dcm文件
     */
    @GetMapping("/downloadDcm")
    public void downloadDcm(@RequestParam("uuid") String uuid, HttpServletResponse response) {
        apiService.downloadDcm(uuid, response);
    }

    /**
     * 融合软件上传图片
     */
    @PostMapping("/capture")
    public AjaxResult capture(@RequestBody MedicalCapture capture) {
        System.out.println("capture方法已被执行");
        apiService.handleImageCaptute(capture);
        return AjaxResult.success();
    }


    @GetMapping("/images")
    public AjaxResult getImages(@RequestParam("StudyInsta") String studyInsta) {
        return apiService.getImage(studyInsta);
    }

    /**
     * 图片对应的数字从1开始
     */
    @GetMapping("/imagesMap")
    public AjaxResult getImagesMap(@RequestParam("StudyInsta") String studyInsta) {
        return apiService.getImagesMap(studyInsta);
    }

    /**
     * 删除图片的路径
     *
     * @param
     * @return
     */
    @DeleteMapping("/delImages")
    public AjaxResult delImages(@RequestBody List<String> list) {
        return apiService.delImages(list);
    }


    // 获取对应患者的图像以及资料
    @GetMapping("getPatientMessage/{ptdeid}")
    public AjaxResult getPatientMessage(@PathVariable String ptdeid) {
        return apiService.getPatientMessage(ptdeid);
    }


    // 获取报告对应的全部截图
    @GetMapping("/imagesMap2/{im_ptdeid}")
    public AjaxResult getImagesMap2(@PathVariable String im_ptdeid) {

        try {
            List<GetImageDto> pathList = apiService.getImagesMap2(im_ptdeid);
            List<GetImageDto> imageBase64 = new ArrayList<>();


            Map<Integer, GetImageDto> map = new HashMap<>();
            int i = 1;

            for (GetImageDto s : pathList) {
                GetImageDto getImageDto = new GetImageDto();
                getImageDto.setImageID(s.getImageID());
                getImageDto.setImageBase64(getImageAsBase64(s.getImageBase64()));
                getImageDto.setImageDescription(apiService.getImageDescription(s.getImageID()));
                imageBase64.add(getImageDto);
                i++;
            }
            return AjaxResult.success(imageBase64);
        }catch (Exception e){
         return AjaxResult.error("本地未发现指定图像，请上线后再测试");
        }
    }

    // 获取单个截图
    @GetMapping("/Oneimages/{imageName}")
    public AjaxResult getOneImages(@PathVariable String imageName) {

        String imagePath = apiService.getOneImageByname(imageName);
        String imageBase64 = getImageAsBase64(imagePath);
        return AjaxResult.success("操作成功", imageBase64);
    }

    // 获取对应图片的base64编码
    public String getImageAsBase64(String imagePath) {
        File file = new File(imagePath);
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            byte[] bytes = new byte[(int) file.length()];
            fileInputStream.read(bytes);
            return Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 保存图像对应的描述
    @PostMapping("/setImageDescription")
    public AjaxResult setImageDescription(@RequestBody SetImageDecription imageDecription) {
        apiService.setImageDescription(imageDecription);
        return AjaxResult.success("保存成功！");
    }

    // 删除对应图片（将bdel设置为1）
    @PostMapping("/deleteImage")
    public AjaxResult deleteImage(@RequestBody ImageIdDto imageIDList) {
        apiService.deleteImage(imageIDList);
        return AjaxResult.success("删除成功！");
    }

    // 打印输出word文档
    @PostMapping("/printWord")
    public AjaxResult printWord(@RequestBody PrintWordDto printWordDto) throws IOException, InvalidFormatException {
        // 根据名称列表获取对应的路径列表

        List<String> imagePathList = new ArrayList<>();
        for (String id : printWordDto.getImageIdList()) {
            imagePathList.add(apiService.getOneImage(id));
        }

        // 根据报告id获取姓名、年龄、性别、检查日期、检查号
        GetWordMessageDto message = apiService.getWordMessage(printWordDto.getPtdeid());

        // 准备数据
        Map<String, String> map = new HashMap<>();
        map.put("name", message.getPtName());
        map.put("age", message.getPtdtAge());
        map.put("sex", message.getPtSex());
        map.put("date", message.getPtdtCheckDate().substring(0, 10));
        map.put("checkcode", message.getPtdtCheckCode());

        // 模板路径以及输出路径
        String templateFilePath = "/www/wwwroot/yunjiaopei/REPORT/PETCT图像.docx";

        // 获取当前时间
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyMMddHHmmss");

        // 定义要保存的文件名和路径
        String fileName = message.getPtdtCheckCode() + "_" + message.getPtName() + "_" + formatter.format(date) + "_" + "图册报告.docx";
        String folderPath = "/www/wwwroot/yunjiaopei/REPORT/temReport";

        ;

        return AjaxResult.success("打印成功！", apiService.insertAndOutFile(templateFilePath, map, fileName, folderPath, imagePathList));
    }

    @Autowired
    private TabPtdetailMapper tabPtdetailMapper;

    // 打印输出文字文档
    @PostMapping("/printWirtingWord/{ptdeid}")
    public AjaxResult printWirtingWord(@PathVariable String ptdeid) throws IOException, InvalidFormatException {

        // 获取数据
        TabPtdetail message = tabPtdetailMapper.selectTabPtdetailByPtdeid(Long.valueOf(ptdeid));
        // 根据报告id获取姓名、年龄、性别、检查日期、检查号
        GetWordMessageDto message2 = apiService.getWordMessage(ptdeid);

        // 准备数据
        Map<String, String> map = new HashMap<>();
        map.put("ptdeid", ptdeid);
        map.put("name", message2.getPtName());
        map.put("sex", message2.getPtSex());
        map.put("age", message2.getPtdtAge());
        map.put("checkdate", message2.getPtdtCheckDate().substring(0, 10));
        map.put("hosptial", "医院");
        map.put("ments", message.getPtdtSqdept());
        map.put("hoscode", message.getPtdtInhoscode());
        map.put("xxj", message.getPtdtXxjtxt());
        map.put("dosage", message.getPtdtDosage());
        map.put("lcdiagnous", message.getPtdtLcdiagnoustxt());
        map.put("checkbw", message.getPtdtCheckbw());
        map.put("shsjTxt", message.getPtdtShsjtxt());
        map.put("shyjTxt", message.getPtdtShyjtxt());

        // 模板路径以及输出路径
        String templateFilePath = "/www/wwwroot/yunjiaopei/REPORT/PET文字模板.docx";

        // 定义要保存的文件名和路径
        String fileName = ptdeid + "_" + message2.getPtName() + "文字报告.docx";
        String folderPath = "/www/wwwroot/yunjiaopei/REPORT/writingReport";

        return AjaxResult.success("打印成功！", apiService.insertAndOutFileWriting(templateFilePath, map, fileName, folderPath));
    }


    // 根据报告id获取检查日期
    @GetMapping("/getPtdtCheckDate/{ptdeid}")
    public AjaxResult getPtdtCheckDate(@PathVariable String ptdeid) {
        return AjaxResult.success(apiService.getPtdtCheckDate(ptdeid).substring(0, 19));
    }

    // 获取随访的标签以及随访结果
    @GetMapping("/getFollow/{ptdeid}")
    public AjaxResult getFollow(@PathVariable String ptdeid) {
        ExamSurveyDto examSurveyDto = apiService.getFollow(ptdeid);
        if (examSurveyDto == null) {
            return AjaxResult.success("患者数据不存在",null);
        }
        return AjaxResult.success(examSurveyDto);
    }

    // 保存随访结果
    @PostMapping("/updateFollow")
    public AjaxResult getFollow(@RequestBody ExamSurveyDto examSurveyDto) {

        // 如果标签不符合则返回错误，否则进行下一步
        if ("未随访".equals(examSurveyDto.getFollowTag()) || "无进一步治疗".equals(examSurveyDto.getFollowTag()) || "符合".equals(examSurveyDto.getFollowTag()) || "需再次随访".equals(examSurveyDto.getFollowTag()) || "不符合".equals(examSurveyDto.getFollowTag())) {
            // 如果数据库中不存在，则自动插入
            ExamSurveyDto examSurveyDto1 = apiService.getFollow(examSurveyDto.getSurPtdeid());
            if (examSurveyDto1 == null) {
                return apiService.insertFollow(examSurveyDto);
            } else {
                // 存在则更新
                return apiService.updateFollow(examSurveyDto);
            }
        }
        return AjaxResult.error("标签内容有误");
    }

    // 获取问诊数据
    @GetMapping("/getwzdata/{ptdeid}")
    public AjaxResult getwzdata(@PathVariable String ptdeid) {
        WzDataDto wzDataDto = apiService.getwzdata(ptdeid);
        return AjaxResult.success(wzDataDto);
    }

    // 保存问诊数据
    @PostMapping("/updatewzdata")
    public AjaxResult getwzdata(@RequestBody WzDataDto wzDataDto) {
        return AjaxResult.success(apiService.updatewzdata(wzDataDto));
    }


    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    @PostMapping("/uploadImage")
    public AjaxResult upload(MultipartFile file, String ptdeid) {
        return apiService.upload(file, ptdeid);
    }

    /**
     * 查询已存在的分类
     *
     * @return
     */
    @GetMapping("/getCheckMachineList")
    public AjaxResult getCheckMachineList() {
        CheckMachineDto checkMachineDto = apiService.getCheckMachineList();
        return AjaxResult.success(checkMachineDto);
    }
}
